package com.lz.zookeeper;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

/**
 * zk连接状态监听器
 * @author likejian
 *
 */
public class ZooKeeperConnectionStateListener implements ConnectionStateListener {
	
	private static Logger LOG = LoggerFactory.getLogger(ZooKeeperConnectionStateListener.class);
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static Gson gson = new Gson();
	private String zkRegPath;
	private ZookeeperRegContent regContent;

	public ZooKeeperConnectionStateListener(String zkRegPath, ZookeeperRegContent regContent) {
		this.zkRegPath = zkRegPath;
		this.regContent = regContent;
	}

	@Override
	public void stateChanged(CuratorFramework curator,
			ConnectionState connectionState) {
		if (connectionState == ConnectionState.LOST) {
			while (true) {
				try {
					if (curator.getZookeeperClient().blockUntilConnectedOrTimedOut()) {
						LOG.info("==============正在重新注册==============");
						regContent.setReg_time(sdf.format(new Date()));
						String path = ZooKeeperUtil.createNode(curator, zkRegPath, 
								gson.toJson(regContent).getBytes(), CreateMode.EPHEMERAL_SEQUENTIAL);
						LOG.info("==============重新注册==============path=" + path);
						LOG.info("==============重新注册结束==============");
						break;
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
					LOG.error(ExceptionUtils.getFullStackTrace(e));
					break;
				} catch (Exception e) {
					e.printStackTrace();
					LOG.error(ExceptionUtils.getFullStackTrace(e));
				}
			}
		}
	}
}